package com.etlmaster.executor.steps.sql;

/**
 * 用于在oracel数据库中创建sequence 并绑定某个列，实现自增功能
 */
import java.util.Map;

import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.StepState;
import com.etlmaster.jdbc.JdbcTemplate;
/**
 * @author Wugf
 * @date 2016-03-08
 */
@StepInstruction("sequence")
public class CreateSequenceStep extends Step {

	
	private CreateSequenceStepMeta meta;

	public CreateSequenceStep(StepMeta meta) {
		super(meta);
		this.meta = (CreateSequenceStepMeta) meta;

	}

	@Override
	protected int handle() {

		JdbcTemplate jdbc = new JdbcTemplate(meta.getDsName());

		String selSql = "select " + meta.getName() + ".nextVal from sys.dual";
		boolean isExist = true;
		try {
			Map<String, Object> map = jdbc.queryForMap(selSql);
		} catch (Exception e) {
			isExist = false;
			meta.log("ERROR","{}",e.getMessage());
		}
		if (!isExist) {
			String seqSql = "create sequence " + meta.getName() + " minValue "
					+ meta.getMinValue() + " maxValue " + meta.getMaxValue()
					+ " start with " + meta.getStartValue() + " increment by "
					+ meta.getIncrement() + " ";
			int row = jdbc.update(seqSql);
			meta.log("INFO","{},{}", row+"", seqSql);
			
		} else {
			meta.log("INFO","Sequence :{}已经存在，不重复创建");
			String triggerSql = "create or replace trigger " + meta.getTableName()+"_"+meta.getColName()
					+ " before insert on " + meta.getTableName()
					+ " for each row " + " begin " + " select "
					+ meta.getName() + ".nextVal " + " into :NEW."
					+ meta.getColName() + " from sys.dual;" + " end ;";
			meta.log("INFO",triggerSql);
			jdbc.update(triggerSql);
		}
		return StepState.RUNNING_SUCCESSED;
	}

	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}

}
